package history

import (
	"io/ioutil"
	"os"

	//"sync"
	"time"

	"github.com/AndreasBriese/bbloom"
)

//BloomHistory bloom
type BloomHistory struct {
	//locker *sync.Mutex
	Path  string
	Bloom bbloom.Bloom
}

func (history *BloomHistory) Close() {
	bytes := history.Bloom.JSONMarshal()
	ioutil.WriteFile(history.Path, bytes, 0666)
}

//NewBloomHistory bloom
func NewBloomHistory(bloomPath string) *BloomHistory {
	_, err := os.Stat(bloomPath)
	var bf bbloom.Bloom
	if err == nil {
		json, _ := ioutil.ReadFile(bloomPath)
		bf = bbloom.JSONUnmarshal(json)
	} else {
		bf = bbloom.New(float64(10000000), float64(0.000000001))
	}
	return &BloomHistory{
		Path:  bloomPath,
		Bloom: bf,
	} //locker: new(sync.Mutex)}
}

//GetRegisteredCount url count
func (history *BloomHistory) GetRegisteredCount() int64 {
	return int64(history.Bloom.ElemNum)
}

//Register url
func (history *BloomHistory) Register(url string) bool {
	return !history.Bloom.AddIfNotHas([]byte(url))
}

//Update url
func (history *BloomHistory) Update(url string, state string, lastModifyTime time.Time) {

}
